package com.consumerzk.consumerzk.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.test.entity.RpcRequest;
import com.common.test.zk.RegistryCenterConfig;
import com.consumerzk.consumerzk.entity.ServerTimeEntity;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;

public class RpcConsumerZk {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //private  UserClientHandler userClientHandler;

    private static CuratorFramework curatorFramework;


    private List<UserClientHandler> userClientHandlers=new ArrayList<>();

    public List<UserClientHandler> getUserClientHandlers() {
        return userClientHandlers;
    }

    public void setUserClientHandlers(List<UserClientHandler> userClientHandlers) {
        this.userClientHandlers = userClientHandlers;
    }

    public Object createProxy(final Class<?> serviceClass) throws ClassNotFoundException {
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法
                int size = userClientHandlers.size();
                 int random = new Random().nextInt(2);
                System.out.println(random);
                //UserClientHandler userClientHandler = userClientHandlers.get(random);
                //记录请求日志到zk  选出我们需要的zk
                UserClientHandler userClientHandler=loadBlance(userClientHandlers);
                // 设置参数
                RpcRequest rpcRequest =new RpcRequest();
                rpcRequest.setRequestId(serviceClass.getName());
                rpcRequest.setClassName(serviceClass.getName());
                Class[] argTypes=new Class[args.length];
                for (int i = 0; i < args.length; i++) {
                    argTypes[i]=args[i].getClass();
                }
                rpcRequest.setParameters(args);
                rpcRequest.setParameterTypes(argTypes);
                rpcRequest.setMethodName(method.getName());
                userClientHandler.setRpcRequest(rpcRequest);

                // 去服务端请求数据
                Long startTime=System.currentTimeMillis();
                 Object o = executor.submit(userClientHandler).get();
                 Long endTime=System.currentTimeMillis();
                 addOrUpdateElement(userClientHandler.getServerPort(),userClientHandler.getServerIP(),endTime-startTime,endTime);

                return o;
            }
        });


    }


private UserClientHandler loadBlance(List<UserClientHandler> userClientHandlers) throws Exception {
        if (null==curatorFramework){
            curatorFramework = CuratorFrameworkFactory.builder()
                    .connectString(RegistryCenterConfig.CONNECTING_STR)
                    .sessionTimeoutMs(RegistryCenterConfig.SESSION_TIMEOUT)
                    .retryPolicy(new ExponentialBackoffRetry(1000, 10)).build();
            curatorFramework.start();
        }
    //获取某个节点
    String path=RegistryCenterConfig.NAMESPACE+"/TIME";
    //如果serviceNodePath（/rpcNode/userService）不存在就创建
    Stat stat = curatorFramework.checkExists().forPath(path);
    if (stat==null){
        //持久化节点
        //curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path,RegistryCenterConfig.DEFAULT_VALUE);
        return userClientHandlers.get(0);
    }
    UserClientHandler result=null;
    Long temWorkTime=0L;
    for (UserClientHandler userClientHandler : userClientHandlers) {
        String serverIP = userClientHandler.getServerIP();
         String serverPort = userClientHandler.getServerPort();
         path=path+"/"+serverIP+":"+serverPort;
         stat = curatorFramework.checkExists().forPath(path);
         if (null==stat){
             return userClientHandler;
         }
         byte[] bytes = curatorFramework.getData().forPath(path);
         if (null==bytes){
             return userClientHandler;
         }
         ServerTimeEntity object = JSON.parseObject(bytes, ServerTimeEntity.class);
         long nowTime = System.currentTimeMillis();
         Long serverEndTime = object.getServerEndTime();
         if (nowTime-serverEndTime>=5000){
             return userClientHandler;
         }
         if (!temWorkTime.equals(0)&&temWorkTime>object.getWorkTime()){
             result=userClientHandler;
         }else {
             temWorkTime=object.getWorkTime();
         }

    }
    if (null==result){
        result=userClientHandlers.get(0);
      }

    return result;
}


private void addOrUpdateElement(String serverPort,String ip,Long workTime,Long endTime) throws Exception {
    String path=RegistryCenterConfig.NAMESPACE+"/TIME/"+ip+":"+serverPort;
    Stat stat = curatorFramework.checkExists().forPath(path);
    ServerTimeEntity serverTimeEntity=new ServerTimeEntity();
    serverTimeEntity.setServerEndTime(endTime);
    serverTimeEntity.setServerIpPort(ip);
   serverTimeEntity.setWorkTime(workTime);
    if (null==stat){
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path,JSON.toJSONBytes(serverTimeEntity));
    }else {
        curatorFramework.setData().forPath(path,JSON.toJSONBytes(serverTimeEntity));
    }
}


}
